package cn.echoedu.control;

import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import cn.echoedu.entity.RequestMessage;
import cn.echoedu.entity.User;
import cn.echoedu.entity.receivecommand.LoginReceive;
import cn.echoedu.util.L;

public class RequestMessageControl extends BaseControl{
	private final String T = "RequestMessageControl----------->";
	
	public void savedRequestMessage(HttpServletRequest request,
			LoginReceive loginreceive,User user){
		L.p(T+"savedRequestMessage");
		RequestMessage newrequestmessage=new RequestMessage();
		newrequestmessage.setMime(loginreceive.getMIME());
		newrequestmessage.setMname(loginreceive.getNAME());
		newrequestmessage.setIp(request.getRemoteAddr());
		newrequestmessage.setUser(user);
	    newrequestmessage.setToken(generateToken(loginreceive));
		String agent=request.getHeader("user-agent");
		StringTokenizer st = new StringTokenizer(agent,";"); 
		st.nextToken();
		try{
			newrequestmessage.setBrowser(st.nextToken());
			newrequestmessage.setOs(st.nextToken());
		}catch(Exception e){
			e.printStackTrace();
		}
		RequestMessage oldrequestmessage = queryByUserNumber(loginreceive.getUser_number());
		L.p(T+"savedRequestMessage+++oldrequestmessage="+oldrequestmessage);
		if(isNull(oldrequestmessage)){
			getRequestMessageModel().insertRunning(newrequestmessage);
		}else{
			getRequestMessageModel().update(oldrequestmessage,newrequestmessage);
		}
	}
	private boolean isNull(Object object){
		return object==null?true:false;
	}
	private String generateToken(LoginReceive loginreceive) {
		// TODO Auto-generated method stub
		return loginreceive.getMIME()+loginreceive.getApiKey()
				+loginreceive.getUser_number();
	}
	public boolean validateApiKey(String apikey){
		return getAppApiModel().queryByApiKey(apikey);
	}
	public boolean validateToken(String token) {
		// TODO Auto-generated method stub
		return getRequestMessageModel().queryByToken(token);
	}
	public RequestMessage queryByUserNumber(String usernumber){
		final String M="queryByUserNumber";
		L.p(T+M);
		return getRequestMessageModel().queryByUserNumber(usernumber);
	}

}
